package ljl.bilibili.gateway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import ljl.bilibili.client.notice.SendNoticeClient;
import ljl.bilibili.entity.user_center.user_info.Privilege;
import ljl.bilibili.entity.user_center.user_info.User;
import ljl.bilibili.gateway.constant.Constant;
import ljl.bilibili.gateway.service.RegisterService;
import ljl.bilibili.gateway.vo.request.PasswordRegisterRequest;
import ljl.bilibili.mapper.user_center.user_info.PrivilegeMapper;
import ljl.bilibili.mapper.user_center.user_info.UserMapper;
import ljl.bilibili.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RegisterServiceImpl implements RegisterService {
    @Resource
    UserMapper userMapper;
    @Resource
    PrivilegeMapper privilegeMapper;
    @Resource
    SendNoticeClient client;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 账号密码注册，并发送新增用户的数据同步消息
     */
    @Transactional
    @Override
    public Result<Integer> passwordRegister(PasswordRegisterRequest passwordRegisterRequest) {
        // 参数校验：确保用户名和密码不为空
        if (passwordRegisterRequest == null || StringUtils.isBlank(passwordRegisterRequest.getUserName()) || StringUtils.isBlank(passwordRegisterRequest.getPassword())) {
            return Result.error("用户名或密码不能为空");
        }
        //定义分布式锁的key
        String lockKey = "register_lock:" + passwordRegisterRequest.getUserName();
        try {
            //尝试获取分布式锁,防止并发注册
            if (!redisTemplate.opsForValue().setIfAbsent(lockKey, "locked", 3, TimeUnit.SECONDS)) {
                return Result.error("请勿频繁注册");
            }
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getUserName, passwordRegisterRequest.getUserName());
            if (userMapper.selectOne(wrapper) != null) {
                return Result.error("该用户已存在");
            } else {
                //创建用户并加密密码
                User user = passwordRegisterRequest.toEntity();
                user.setPassword(passwordEncoder.encode(user.getPassword()));
                try {
                    userMapper.insert(user);
                } catch (DuplicateKeyException e) {
                    //当尝试插入重复用户名时，数据库会抛出唯一性冲突异常，捕获数据库异常
                    return Result.error("该用户已存在");
                }
//            CompletableFuture<Void> sendDBChangeNotice = CompletableFuture.runAsync(() -> {
                //发送新增用户数据同步消息
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> map = objectMapper.convertValue(user, Map.class);
                map.put(Constant.TABLE_NAME, Constant.USER_TABLE_NAME);
                map.put(Constant.OPERATION_TYPE, Constant.OPERATION_TYPE_ADD);
                //去除一些不需要同步的字段
                map.remove(Constant.TABLE_IGNORE_USERNAME);
                map.remove(Constant.TABLE_IGNORE_PASSWORD);
                map.remove(Constant.TABLE_IGNORE_PHONE_NUMBER);
                map.remove(Constant.TABLE_IGNORE_MAIL_NUMBER);
                client.sendDBChangeNotice(map);
//            });
                privilegeMapper.insert(new Privilege().setUserId(user.getId()));
                return Result.data(user.getId());
            }
        } finally {
            //释放分布式锁
            redisTemplate.delete(lockKey);
        }
    }
}
